package com.microservice.auth.jwt.userDetails;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.microservice.api.system.RemoteSystemService;
import com.microservice.core.domain.AjaxResult;
import com.microservice.model.system.Permission;
import com.microservice.model.system.Role;
import com.microservice.model.system.User;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AccountUserDetailsService implements UserDetailsService {

    @Resource
    private RemoteSystemService remoteSystemService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AjaxResult ajaxResult = remoteSystemService.getUserByUsername(username);
        if (ajaxResult == null || ajaxResult.isError()) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        User user = JSONObject.parseObject(String.valueOf(ajaxResult.get("data")), User.class);
        return new AccountUser(user.getId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getUsername()));
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     */
    public List<GrantedAuthority> getUserAuthority(String username) {
        //自定义操作权限字符收集
        AjaxResult ajaxResult = remoteSystemService.getPermissionByUsername(username);
        String jsonStringPermission = JSON.toJSONString(ajaxResult);
        JSONObject jsonObjectPermission = JSON.parseObject(jsonStringPermission);
        String dataStringPermission = jsonObjectPermission.getString("data");
        List<Permission> permissions = JSON.parseArray(dataStringPermission, Permission.class);
        List<String> urls = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(permissions)) {
            //自定义操作权限字符比如 sys:user:list 或者 /user/list
            urls = permissions.stream().map(Permission::getUrl).toList();
        }

        //角色字符收集
        AjaxResult roleResult = remoteSystemService.getRoleByUsername(username);
        String jsonStringRole = JSON.toJSONString(roleResult);
        JSONObject jsonObjectRole = JSON.parseObject(jsonStringRole);
        String dataStringRole = jsonObjectRole.getString("data");
        List<Role> roles = JSON.parseArray(dataStringRole, Role.class);
        List<String> roleNames = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roles)) {
            // spring security 在判断角色时会自动截取ROLE_,你的角色字符必须是ROLE_开头,
            // 比如ROLE_admin,ROLE_normal 表示超级管理员角色和普通用户角色(非超管)
            //如果角色字符不是ROLE_开头,那么就需要自定义DefaultMethodSecurityExpressionHandler实现权限比较了
            roleNames = roles.stream().map(Role::getName).toList();
        }

        List<String> combinedList = new ArrayList<>(roleNames);
        combinedList.addAll(urls);
        String authority = String.join(",", combinedList);
        System.out.println("用户的权限和角色列表为：" + authority);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
